import { Banner } from '../models';
import redis from '../utils/redis';

export default function (router) {
  /**
   * 前端接口
   * 获取banner列表
   */
  router.get('/api/front/banner', async ctx => {
    // 如果存在缓存直接返回
    const cacheData = await redis.get('banner-data');
    if (cacheData) {
      await ctx.json(true, '获取轮播图成功', { ...JSON.parse(cacheData), cached: true });
      return;
    }
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const list = await Banner.find({}, '-url_params')
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ priority: 1, show: -1, create_time: 1 });
    const total = await Banner.countDocuments();
    // 设置缓存值
    redis.set('banner-data', JSON.stringify({ list, total }), 'EX', 60 * 10);
    await ctx.json(true, '获取轮播图成功', { list, total });
  });

  /**
   * 后端接口
   * 获取banner列表
   */
  router.get('/api/admin/banner', async ctx => {
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const { search } = ctx.request.query;
    const queryParam = {};
    if (search) {
      const reg = new RegExp(search.toString('utf8').trim(), 'i');
      queryParam.des = reg;
    }
    const list = await Banner.find(queryParam)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ priority: 1, show: -1, create_time: 1 });
    const total = await Banner.countDocuments();
    await ctx.json(true, '获取轮播图成功', { list, total });
  });

  /**
   * 后端接口
   * 新增轮播图
   */
  router.post('/api/admin/banner', async ctx => {
    let { show, url, url_params, img_url, background, des } = ctx.request.body;
    let maxPriority = await Banner.countDocuments();
    let result = await Banner.create({
      priority: maxPriority + 1,
      show,
      url,
      url_params,
      background,
      img_url,
      des,
      create_time: new Date()
    });
    await ctx.json(true, '新增轮播图成功', { result, total: maxPriority + 1 });
  });

  /**
   * 后端接口
   * 修改轮播图
   */
  router.put('/api/admin/banner/:id', async ctx => {
    const id = ctx.params.id;
    const result = await Banner.updateOne({ _id: id }, { $set: ctx.request.body });
    if (result.ok === 1) {
      const newest = await Banner.findById(id);
      await ctx.json(true, '更新轮播图成功', newest);
    } else {
      await ctx.json(false, '更新轮播图失败', result);
    }
  });

  /**
   * 后端接口
   * 删除轮播图
   */
  router.delete('/api/admin/banner/:id', async ctx => {
    const id = ctx.params.id;
    const thisData = await Banner.findOne({ _id: id }, 'priority');
    const operation = await Banner.deleteOne({ _id: id });
    // 更新顺序
    const update = await Banner.updateMany({ priority: { $gt: thisData.priority } }, { $inc: { priority: -1 } });
    if (operation.ok && update.ok) {
      await ctx.json(true, '删除轮播图成功');
    } else {
      await ctx.json(false, '删除轮播图失败');
    }
  });

  /**
   * 后端接口
   * 交换轮播图位置
   */
  router.post('/api/admin/banner/exchange', async ctx => {
    const { from: fromIndex, to: toIndex, id } = ctx.request.body;
    if (!fromIndex || !toIndex) await ctx.json(false, '参数错误');
    if (fromIndex === toIndex) await ctx.json(false, '交换顺序不能相同');

    let updateCur, updateOther;
    if (fromIndex > toIndex) {
      updateOther = await Banner.updateMany({ priority: { $lt: fromIndex, $gte: toIndex } }, { $inc: { priority: 1 } });
      updateCur = await Banner.updateOne({ _id: id }, { $set: { priority: toIndex } });
    } else {
      updateOther = await Banner.updateMany({ priority: { $gt: fromIndex, $lte: toIndex } }, { $inc: { priority: -1 } });
      updateCur = await Banner.updateOne({ _id: id }, { $set: { priority: toIndex } });
    }

    if (updateCur.ok && updateOther.ok) {
      await ctx.json(true, '交换成功');
    } else {
      await ctx.json(false, '交换失败');
    }
  });
}
